public interface Greeting { void greet(String name); default void sayHello(String name) { System.out.println("Hello, " + name); } } public class HelloWorld implements Greeting { @Override public void greet(String name) { System.out.println("Welcome, " + name); } @Override public void sayHello(String name) { System.out.println("Hi, " + name); } public static void main(String[] args) { HelloWorld helloWorld = new HelloWorld(); helloWorld.greet("John"); helloWorld.sayHello("John"); } }
Output:
Welcome, John
Hi, John
In the interface, static methods can also be defined. Utility methods are defined using static methods.
public interface MyInterface { void myMethod(); static void myStaticMethod() { System.out.println("This is a static method inside MyInterface."); } } public class MyClass implements MyInterface { public void myMethod() { System.out.println("This is MyClass implementation of myMethod."); } } public class Main { public static void main(String[] args) { MyClass obj = new MyClass(); obj.myMethod(); // call the static method without creating an object MyInterface.myStaticMethod(); } }
In the above example, we declare a static method myStaticMethod() inside the interface MyInterface. We can call this static method without creating an object of any implementing class, using the interface name followed by the method name (MyInterface.myStaticMethod()).
It is significant to note that interface static methods can only be accessed by their interface name and cannot be overridden by implementing classes. Furthermore, because they are not connected to any specific instance of the interface, static methods cannot access instance variables or instance methods of the interface.
Static methods in interfaces can be useful for providing utility methods that are related to the interface but are not specific to any implementing class.
Output:
This is MyClass implementation of myMethod.
This is a static method inside MyInterface.
Post your comment